import React, { useState, useEffect } from 'react';
import { TjForm } from '@/tjComponents';
import { Button, Form, message } from 'antd';
import { useThrottleFn } from 'ahooks';
import { formItems } from './helper';
// 该文件为js 解决编辑器标红问题
// @ts-ignore
import { HttpCode } from '#/utils/contacts';
// @ts-ignore
import { getListStatementTypeByProvinceId, getListTransactionAttributes } from '../../services';
import type { BaseButtonProps } from 'antd/lib/button/button';
import type { Store } from 'antd/lib/form/interface';
import _ from 'lodash';
import './index.less';
import { formUtils } from '@/tjComponents/TjForm/helper';

const DrawerContent: React.FC<IDrawerContentProps> = (props) => {
  const [form] = Form.useForm();
  const [optionsData, setOptionsData] = useState<any>();

  const { run } = useThrottleFn(() => submit(), { wait: 1000 });

  const handleSelectChange = async (option: any, isInit?: boolean) => {
    if (option.marketId) {
      if (!isInit) {
        form.setFieldsValue({ statementCode: undefined, statementTypeName: undefined });
      }

      try {
        const [statementTypeRes, transactionAttributesRes] = await Promise.all([
          getListStatementTypeByProvinceId(option.marketId),
          getListTransactionAttributes(option.marketId),
        ]);

        if (
          statementTypeRes?.statusCode === HttpCode.SUCCESS &&
          transactionAttributesRes?.statusCode === HttpCode.SUCCESS
        ) {
          const obj = {
            ...props.optionsData,
            getListStatementTypeByProvinceId: statementTypeRes.data,
            listTransactionAttributes: transactionAttributesRes.data,
          };
          setOptionsData(obj);
        } else {
          if (statementTypeRes?.statusCode !== HttpCode.SUCCESS) {
            message.error(statementTypeRes?.message || '获取结算科目失败');
          }
          if (transactionAttributesRes?.statusCode !== HttpCode.SUCCESS) {
            message.error(transactionAttributesRes?.message || '获取交易属性失败');
          }
        }
      } catch (error) {
        message.error('获取数据失败');
      }
    }
  };

  const submit = () => {
    form.validateFields().then((res) => {
      const newData = formUtils.handleValues(res, true, true);
      props.submit(newData);
    });
  };

  // 表单所有数据变化
  const onValuesChange = (changedValues: any, values: any) => {
    if (changedValues['statementTypeId|statementTypeName'] === '') {
      form.setFieldsValue({ statementCode: '' });
    }
    if (changedValues['statementTypeId|statementTypeName']) {
      const arr = optionsData.getListStatementTypeByProvinceId || [];
      const item = _.find(
        arr,
        (n: any) => n.value === changedValues['statementTypeId|statementTypeName'].statementTypeId,
      );
      if (item) {
        form.setFieldsValue({ statementCode: item.code });
      }
    }
    if (changedValues['marketId|marketName']) {
      const newFormData = {
        'statementTypeId|statementTypeName': undefined,
        statementCode: undefined,
      };
      form.setFieldsValue(newFormData);
    }
  };

  useEffect(() => {
    if (props.values) {
      handleSelectChange({ marketId: props.values?.marketId }, true);
    } else {
      setOptionsData(props.optionsData);
    }
  }, []);

  return (
    <div className="drawer-content">
      <div className="title">基本信息</div>
      <div className="form-box">
        <TjForm
          onValuesChange={onValuesChange}
          useGrid={{
            row: {
              gutter: 40,
            },
            col: {
              span: 8,
            },
          }}
          layout="vertical"
          form={form}
          initialValues={{ ...props.values }}
          items={formItems(optionsData, false, handleSelectChange)}
        />
      </div>
      <div className="btn">
        <Button
          style={{ width: 98, height: 32 }}
          type="primary"
          onClick={run}
          loading={props.loading}
        >
          提交
        </Button>
      </div>
    </div>
  );
};

interface IDrawerContentProps {
  loading?: BaseButtonProps['loading'];
  submit: (values: Store) => void;
  // marketingUnit 交易单元数据
  optionsData?: { marketingUnit: any[] };
  values?: any;
  marketId?: string;
}

export default DrawerContent;
